package com.cedifie.lendapp.ui.loan.impl

import android.content.Context
import com.cedifie.lendapp.MyApplication
import com.cedifie.lendapp.R
import com.cedifie.lendapp.http.IHttpCallback
import com.cedifie.lendapp.mvp.presenter.MvpPresenter
import com.cedifie.lendapp.ui.loan.view.ICedLoanCommonView
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lendapp.utils.status.StatusRepository
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:45
 * @Annotation：审核中、拒绝、放贷中、放贷中法语 Presenter 实现
 */
class CedLoanCommonPresenterImpl(context: Context?) : MvpPresenter<ICedLoanCommonView>(context) {

    private var model: CedLoanCommonModelImpl? = null

    init {
        model = CedLoanCommonModelImpl()
    }

    /**
     * 检查当前状态
     */
    fun checkCedOrderOrApplyStatusAction(data: JSONObject){
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        //1、判断是否存在 订单状态
        if (data.has("orderStatus")) {
            val orderStatus = data.optString("orderStatus")
            //放款中
            if (StatusRepository(null, orderStatus).isDisbursing()) {
                mvpView?.showCedLoanLendingView()
                return
            }
            //申请贷款被拒绝
            if (StatusRepository(null, orderStatus).isRejected()) {
                mvpView?.showCedLoanFailedView()
                return
            }
        }

        //2、判断是否存在 贷款申请状态
        if (data.has("applyStatus")){
            val applyStatus = data.optString("applyStatus")
            //审核中
            if (StatusRepository(applyStatus).isReviewing()){
                mvpView?.showCedLoanAuditView()
                return
            }
            //被拒绝
            if (StatusRepository(applyStatus).isRejected()){
                mvpView?.showCedLoanFailedView()
                return
            }
        }

        //都不存在 ->  显示被拒绝
        mvpView?.showCedLoanFailedView()
    }

    /**
     * 获取贷款信息
     */
    fun loadCedLoanInfoAction(){
        model?.loadCedLoanInfoAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        obj?.let {
                            mvpView?.showCedLoanInfoData(it)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                loadCedLoanAccountAction()
            }
        })
    }

    /**
     * 获取已绑定的账户列表
     */
    fun loadCedLoanAccountAction(){
        model?.loadCedLoanAccountAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val array = data.optJSONArray("obj")
                        if (array != null && array.length() > 0) {
                            val accountList = arrayListOf<JSONObject>()
                            for (i in 0..<array.length()){
                                accountList.add(array.optJSONObject(i))
                            }
                            mvpView?.showCedLoanAccountList(accountList)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitCedBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        model?.submitCedBindAccountAction(mobile,walletChannel,bindFlag,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadCedLoanAccountAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()

                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val spData = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_COMMON)
                                if (spData.isEmpty()){
                                    return
                                }
                                val commonData = JSONObject(spData)
                                val customize = commonData.optJSONObject("customize")
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        mvpView?.showCedBingAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteCedAccountAction(ids: String) {
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        model?.deleteCedAccountAction(ids,object: IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.showCedToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        //刷新列表
                        loadCedLoanAccountAction()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    fun checkClearUserDataAction(isShowButton: Boolean){
        model?.clearUserDataAction(isShowButton, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//成功
                        if (isShowButton){
                            val obj = data.optJSONObject("obj")
                            if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                                mvpView?.showCedClearUserDataButton(true)
                            } else {
                                mvpView?.showCedClearUserDataButton(false)
                            }
                        } else {
                            mvpView?.showCedClearUserDataSuccess()
                        }
                    }
                    else -> {//失败
                        mvpView?.showCedToast(data.optString("msg"))
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }
}